<?php

namespace App\Http\Controllers;

use App\Services\SearchService;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

class SearchController extends Controller
{
    protected SearchService $searchService;

    public function __construct(SearchService $searchService)
    {
        $this->searchService = $searchService;
    }

    /**
     * 搜索结果页
     */
    public function index(Request $request): Response
    {
        $keyword = $request->input('q');
        
        if (empty($keyword)) {
            return Inertia::render('Shop/SearchResults', [
                'keyword' => '',
                'products' => ['data' => [], 'links' => [], 'meta' => []],
                'filters' => [],
                'hotSearches' => $this->searchService->getHotSearches(10)
            ]);
        }

        // 执行搜索
        $filters = $request->only(['category_id', 'min_price', 'max_price', 'sort']);
        $products = $this->searchService->search($keyword, $filters);

        // 记录搜索历史
        $this->searchService->recordSearchHistory(
            $keyword,
            $products->total(),
            auth()->id(),
            session()->getId()
        );

        // 格式化产品数据
        $formattedProducts = $products->map(function ($product) {
            return [
                'id' => $product->id,
                'name' => $product->name,
                'slug' => $product->slug,
                'description' => $product->description,
                'price' => $product->price,
                'compare_price' => $product->compare_price,
                'discount_percentage' => $product->compare_price && $product->compare_price > $product->price
                    ? round((($product->compare_price - $product->price) / $product->compare_price) * 100)
                    : null,
                'image' => $product->images->where('is_primary', true)->first()?->image_path 
                    ?? $product->images->first()?->image_path 
                    ?? '/images/iphone.jpg',
                'is_featured' => $product->is_featured,
                'categories' => $product->categories->map(fn($cat) => [
                    'id' => $cat->id,
                    'name' => $cat->name,
                    'slug' => $cat->slug,
                ]),
            ];
        });

        return Inertia::render('Shop/SearchResults', [
            'keyword' => $keyword,
            'products' => [
                'data' => $formattedProducts,
                'links' => $products->linkCollection()->toArray(),
                'meta' => [
                    'current_page' => $products->currentPage(),
                    'last_page' => $products->lastPage(),
                    'per_page' => $products->perPage(),
                    'total' => $products->total(),
                ]
            ],
            'filters' => $filters,
            'hotSearches' => $this->searchService->getHotSearches(10)
        ]);
    }

    /**
     * 搜索建议API
     */
    public function suggestions(Request $request)
    {
        $keyword = $request->input('q');
        
        if (strlen($keyword) < 2) {
            return response()->json([]);
        }

        $suggestions = $this->searchService->suggestions($keyword, 5);

        return response()->json(
            $suggestions->map(fn($product) => [
                'id' => $product->id,
                'name' => $product->name,
                'slug' => $product->slug,
            ])
        );
    }

    /**
     * 搜索历史API
     */
    public function history(Request $request)
    {
        $histories = $this->searchService->getSearchHistory(
            auth()->id(),
            session()->getId(),
            10
        );

        return response()->json($histories);
    }

    /**
     * 删除搜索历史
     */
    public function deleteHistory(Request $request, int $id)
    {
        $deleted = $this->searchService->deleteSearchHistory(
            $id,
            auth()->id(),
            session()->getId()
        );

        if ($deleted) {
            return response()->json(['message' => '删除成功']);
        }

        return response()->json(['message' => '删除失败'], 404);
    }

    /**
     * 清空搜索历史
     */
    public function clearHistory(Request $request)
    {
        $this->searchService->clearSearchHistory(
            auth()->id(),
            session()->getId()
        );

        return response()->json(['message' => '清空成功']);
    }

    /**
     * 热门搜索API
     */
    public function hot(Request $request)
    {
        $hotSearches = $this->searchService->getHotSearches(10);

        return response()->json($hotSearches);
    }
}
